<template>
  <div class="">
    <el-card class="header">
      <div>
        <el-button type="primary" size="default" @click="addClick">添加角色</el-button>
      </div>
    </el-card>
    <el-card>
      <el-table :data="allRoles" border style="width: 100%">
        <!--    索引    -->
        <el-table-column label="#" type="index">
        </el-table-column>
        <el-table-column
          prop="name"
          label="角色">
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述">
        </el-table-column>
        <!--    操作    -->
        <el-table-column label="操作" fixed="right" width="300" #default="{ row }">
          <el-button type="primary" size="default" v-permission="['role.distributePermission']" @click="onDistributePermissionClick(row.id)">授权</el-button>
          <el-button type="primary" size="default" @click="onEditClick(row.id)">编辑</el-button>
          <el-button type="danger" size="default"  @click="onRemoveClick(row.id)">删除</el-button>
        </el-table-column>
      </el-table>
    </el-card>
    <distribute-permission :role-id="selectRoleId" v-model="dialogVisible"></distribute-permission>
    <create-role :id="idRef" v-model="roleDialogVisible" @updateData="getRoleList"></create-role>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import DistributePermission from './components/DistributePermission.vue'
import CreateRole from './components/CreateRole.vue'
import { roleList, roleDelete } from '../../../api/role'
import { watchSwitchLang } from '../../../utils/i18n'
const allRoles = ref([])
const getRoleList = async () => {
  allRoles.value = await roleList()
}
const dialogVisible = ref(false)
const roleDialogVisible = ref(false)
const selectRoleId = ref('')
const idRef = ref()
const onDistributePermissionClick = (id: string) => {
  dialogVisible.value = true
  selectRoleId.value = id
}
const onEditClick = async (id: string) => {
  roleDialogVisible.value = true
  idRef.value = id
}
const onRemoveClick = async (id: string) => {
  await roleDelete(id)
  await getRoleList()
}
const addClick = async () => {
  roleDialogVisible.value = true
}
// 保证每次打开dialog 都能重新获取数据
watch(dialogVisible, value => {
  if (!value) selectRoleId.value = ''
})
getRoleList()
watchSwitchLang(getRoleList())
</script>

<style lang="scss" scoped>
.header {
  margin-bottom: 22px;
  text-align: right;
}
</style>
